﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

public partial class EManage : System.Web.UI.Page
{

    public int departId;
    public int positionId;
    public int permissinons;
    public int employeeId;

    protected void Page_Load(object sender, EventArgs e)
    {
        departId = int.Parse(Session["departID"].ToString());
        positionId = int.Parse(Session["positionID"].ToString());
        permissinons = int.Parse(Session["permissions"].ToString());
        employeeId = int.Parse(Session["employeeID"].ToString());

        if (permissinons == 1 || permissinons == 2)
        {
            departId = 1;
        }
        else
        {
            departId = int.Parse(Session["departID"].ToString());
            positionId = int.Parse(Session["positionID"].ToString());
        }

        if (!IsPostBack)
        {
            /*if (positionId != 3)
            {
                if (departId == 2 || departId == 3)
                {
                    departId = 1;
                }*/

            BirthdayRemind birthdayRemind = new BirthdayRemind();
            ArrayList NameList = birthdayRemind.EmployeeNameList(permissinons, departId);
            if (NameList.Count > 0)
            {
                FuncBtnList.Visible = false;
                PanelFunction.Visible = false;
                PanelList.Visible = false;
                ShowBirNamePinel.Visible = true;

                GridView2.DataSource = NameList;
                GridView2.DataBind();
            }
            else
            {
                ShowPannel();

                bind();
                EditEnable();
            }
            DataSet ds = getDataSet();
            DataTable dt = ds.Tables[0];
            BindTree(TreeView1, dt, departId);
        }
    }

    /// <summary>
    /// 创建数据库连接
    /// </summary>
    /// <returns></returns>
    private SqlConnection CreateConn()
    {
        string connStr = ConfigurationManager.ConnectionStrings["ConStr"].ToString();
        SqlConnection conn = new SqlConnection(connStr);

        return conn;
    }

    /// <summary>
    /// 从tb_Department获取FID等于n的DataSet对象
    /// </summary>
    /// <returns></returns>
    private DataSet getDataSet()
    {
        SqlConnection conn = CreateConn();
        DataSet ds = new DataSet();

        try
        {
            string SelectComdStr = "SELECT * FROM tb_Department";
            SqlCommand selectCmd = new SqlCommand(SelectComdStr, conn);

            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = selectCmd;

            da.Fill(ds);
            conn.Close();
        }
        catch (Exception ex)
        {
            conn.Close();
        }

        return ds;

    }

    /// <summary>
    /// 绑定数据到树
    /// </summary>
    /// <param name="treeView">绑定数据的树</param>
    /// <param name="dt">数据源表</param>
    private void BindTree(TreeView treeView, DataTable dt, int partID)
    {
        treeView.Nodes.Clear();//清空节点

        DataRow[] rows = dt.Select("ID=" + partID + "");
        if (rows.Length < 0)
        {
            return;//找不到根节点就返回
        }

        /*TreeNode FatherNode = new TreeNode();
        foreach (DataRow row in rows)
        {
            FatherNode.Text = row["Department"].ToString();
            FatherNode.Value = row["ID"].ToString();
            TreeView1.Nodes.Add(FatherNode);
            CreateChildNode(FatherNode, dt);
        }*/

        TreeNode root = new TreeNode();
        root.Text = rows[0]["Department"].ToString();
        root.Value = rows[0]["ID"].ToString();
        TreeView1.Nodes.Add(root);
        CreateChildNode(root, dt);

        root.Expand();
    }

    /// <summary>
    /// 创建子节点
    /// </summary>
    /// <param name="treeNode">父节点</param>
    /// <param name="dt">存放子节点的数据表</param>
    private void CreateChildNode(TreeNode treeNode, DataTable dt)
    {
        DataRow[] rows = dt.Select("FID='" + treeNode.Value + "'");
        foreach (DataRow row in rows)
        {
            TreeNode Node = new TreeNode();
            Node.Text = row["Department"].ToString();
            Node.Value = row["ID"].ToString();
            treeNode.ChildNodes.Add(Node);
            CreateChildNode(Node, dt);
        }
    }

    /// <summary>
    /// 查找子部门ID
    /// </summary>
    /// <param name="fatherDepartmentID">父ID</param>
    /// <param name="sonDepartmentID">存放子部门ID数组</param>
    private void getSonDepartmentID(int fatherDepartmentID,ref ArrayList sonDepartmentID)
    {
        SqlConnection conn = CreateConn(); 

        string selectPartIDStr = "SELECT ID FROM tb_Department WHERE FID='" + fatherDepartmentID + "'";//查询条件不满足而能查出一张表
        SqlCommand selectPartIDCmd = new SqlCommand(selectPartIDStr, conn);

        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = selectPartIDCmd;

        DataSet ds = new DataSet();
        da.Fill(ds);

        conn.Close();

        /*if (ds.Tables[0].Rows.Count > 0)
        {
            int id = int.Parse(dr[0].ToString());
            sonDepartmentID.Add(id);
            getSonDepartmentID(id, ref sonDepartmentID);
        }
        else
        {

        }*/
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            int id = int.Parse(dr[0].ToString());
            sonDepartmentID.Add(id);
            getSonDepartmentID(id,ref sonDepartmentID);
        }


    }

    /// <summary>
    /// 获得员工信息列表
    /// </summary>
    /// <param name="DepartmentID">员工所在部门</param>
    /// <param name="state">员工状态</param>
    /// <returns></returns>
    private ArrayList getEmployeeInfo(ArrayList DepartmentID,int state)
    {
        ArrayList EmployeeInfoList = new ArrayList();
        SqlConnection conn = CreateConn();

        for (int i = 0; i < DepartmentID.Count; i++)
        {
            string selectCmdStr = "SELECT ID,Name,Sex,Department,Position,TelePhone,Wage FROM tb_EmployeeInfo WHERE department='" + DepartmentID[i] + "' AND State='" + state + "'";
            //string selectCmdStr = "SELECT e.*,p.Position AS Pos,d.Department AS Dep FROM tb_EmployeeInfo e,inner join tb_Position p on e.Position='" + DepartmentID[i] + "'AND e.Position =p.ID AND State='" + state + "' inner join tb_Department d on e.Department=d.ID";
            SqlCommand selectCmd = new SqlCommand(selectCmdStr, conn);

            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = selectCmd;

            DataSet ds = new DataSet();
            da.Fill(ds);

            conn.Close();

            for (int n = 0; n < ds.Tables[0].Rows.Count; n++)
            {
                DataRow dr = ds.Tables[0].Rows[n];
                if ((permissinons == 4 || permissinons == 5 || permissinons == 6) && int.Parse(dr[0].ToString()) == employeeId)
                {
                    continue;
                }

                EmployeeInfo employeeInfoObj = new EmployeeInfo();
                employeeInfoObj.Id = int.Parse(dr[0].ToString());
                //employeeInfoObj.Id = dr[0].ToString();
                employeeInfoObj.Name = dr[1].ToString();
                employeeInfoObj.Sex = dr[2].ToString();
                employeeInfoObj.Department = dr[3].ToString();
                employeeInfoObj.Position = dr[4].ToString();
                employeeInfoObj.TelePhone = dr[5].ToString();
                employeeInfoObj.Wage = dr["Wage"].ToString();
                EmployeeInfoList.Add(employeeInfoObj);
            }
        }

        return EmployeeInfoList;

    }

    /// <summary>
    /// GridView数据绑定
    /// </summary>
    private void bind()
    {
        ArrayList sonDepartmentID = new ArrayList();
        if (sonDepartmentID.Count <= 0)
        {
            sonDepartmentID.Add(departId);
        }

        getSonDepartmentID(departId, ref sonDepartmentID);

        GridView1.DataSource = getEmployeeInfo(sonDepartmentID, Convert.ToInt32(HiddenField1.Value));
        GridView1.DataKeyNames = new string[] { "ID" };
        GridView1.DataBind();

        lb_Allpage.Text = GridView1.PageCount.ToString();
        lb_pageIndex.Text = (GridView1.PageIndex + 1).ToString();
        if (GridView1.PageCount <= 0)
        {
            lb_pageIndex.Text = "0";
            first.Enabled = false;
            prev.Enabled = false;
            next.Enabled = false;
            last.Enabled = false;
        }
        else
        {
            if (GridView1.PageIndex == 0)
            {
                first.Enabled = false;
                prev.Enabled = false;
            }
            else
            {
                first.Enabled = true;
                prev.Enabled = true;
            }

            if (GridView1.PageIndex == GridView1.PageCount - 1)
            {
                next.Enabled = false;
                last.Enabled = false;
            }
            else
            {
                next.Enabled = true;
                last.Enabled = true;
            }
        }
    }

    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        if (((LinkButton)sender).ID == "first")
        {
            GridView1.PageIndex = 0;
            bind();
        }
        else if (((LinkButton)sender).ID == "prev")
        {
            GridView1.PageIndex = GridView1.PageIndex - 1;
            bind();
        }
        else if (((LinkButton)sender).ID == "next")
        {
            GridView1.PageIndex = GridView1.PageIndex + 1;
            bind();
        }
        else if (((LinkButton)sender).ID == "last")
        {
            GridView1.PageIndex = GridView1.PageCount - 1;
            bind();
        }
    }

    protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
    {
        int DepartID = int.Parse(TreeView1.SelectedValue.ToString());

        ArrayList sonDepartmentID = new ArrayList();
        if (sonDepartmentID.Count <= 0)
        {
            sonDepartmentID.Add(DepartID);
        }

        getSonDepartmentID(DepartID, ref sonDepartmentID);

        GridView1.DataSource =getEmployeeInfo( sonDepartmentID,Convert.ToInt32( HiddenField1.Value));
        GridView1.DataBind();
        //GridView1.DataSource = getEmployeeList(DepartID);
        //GridView1.DataBind();
        lb_Allpage.Text = GridView1.PageCount.ToString();
        lb_pageIndex.Text = (GridView1.PageIndex + 1).ToString();

        if (GridView1.PageCount <= 0)
        {
            lb_pageIndex.Text = "0";
            first.Enabled = false;
            prev.Enabled = false;
            next.Enabled = false;
            last.Enabled = false;
        }
        else
        {
            if (GridView1.PageIndex == 0)
            {
                first.Enabled = false;
                prev.Enabled = false;
            }
            else
            {
                first.Enabled = true;
                prev.Enabled = true;
            }

            if (GridView1.PageIndex == GridView1.PageCount - 1)
            {
                first.Enabled = false;
                prev.Enabled = false;
            }
            else
            {
                next.Enabled = true;
                last.Enabled = true;
            }
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Redirect("User_insert.aspx");
    }

    protected void btn_Del_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            GridViewRow row = GridView1.Rows[i];
            bool isCheck = ((CheckBox)row.FindControl("SelectEmployee")).Checked;

            int EmployeeID = Convert.ToInt32(GridView1.DataKeys[GridView1.Rows[i].RowIndex].Value);

            if (isCheck)
            {
                delEmployee(EmployeeID);
            }
        }

        bind();
    }

    /// <summary>
    /// 删除员工
    /// </summary>
    /// <param name="id">员工id</param>
    private void delEmployee(int id)
    {
        SqlConnection conn = CreateConn();

        try
        {
            string delEmployeeCmdStr = "DELETE FROM tb_EmployeeInfo WHERE ID='" + id + "'";
            string delUserCmdStr = "DELETE FROM tb_User WHERE EID='" + id + "'";

            SqlCommand delCmd = new SqlCommand(delEmployeeCmdStr, conn);
            conn.Open();
            delCmd.ExecuteNonQuery();

            delCmd = new SqlCommand(delUserCmdStr, conn);
            delCmd.ExecuteNonQuery();

            conn.Close();

        }
        catch (Exception ex)
        {
            conn.Close();
        }
    }

    /// <summary>
    /// 移动员工到离职或黑名单
    /// </summary>
    /// <param name="id">员工id</param>
    private void MoveEmployee(int id, int state)
    {
        SqlConnection conn = CreateConn();

        try
        {
            string UpdateCmdStr = "UPDATE tb_EmployeeInfo SET State='" + state + "' WHERE ID='" + id + "'";
            string delUserCmdStr = "DELETE FROM tb_User WHERE EID='" + id + "'";

            SqlCommand UpdateCmd = new SqlCommand(UpdateCmdStr, conn);
            conn.Open();
            UpdateCmd.ExecuteNonQuery();

            SqlCommand  delCmd = new SqlCommand(delUserCmdStr, conn);
            delCmd.ExecuteNonQuery();

            conn.Close();
        }
        catch (Exception ex)
        {
            conn.Close();
        }

    }
    protected void btn_removeQuit_Click(object sender, EventArgs e)
    {
        //Button btn = (Button)sender;
        //btn.Attributes.Add("onclick", "return confirm('确定移动到离职吗?');");
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            GridViewRow row = GridView1.Rows[i];
            bool isCheck = ((CheckBox)row.FindControl("SelectEmployee")).Checked;

            int EmployeeID = Convert.ToInt32(GridView1.DataKeys[GridView1.Rows[i].RowIndex].Value);

            if (isCheck)
            {
                MoveEmployee(EmployeeID, 2);
            }
        }

        bind();
    }
    protected void btn_removeBlack_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            GridViewRow row = GridView1.Rows[i];
            bool isCheck = ((CheckBox)row.FindControl("SelectEmployee")).Checked;
            string temp = GridView1.DataKeys[GridView1.Rows[i].RowIndex].ToString();
            int EmployeeID = Convert.ToInt32(GridView1.DataKeys[GridView1.Rows[i].RowIndex].Value);

            if (isCheck)
            {
                MoveEmployee(EmployeeID, 3);
            }
        }

        bind();
    }
    protected void Ibtn_working_Click(object sender, ImageClickEventArgs e)
    {
        if (positionId == -1 || positionId == -2)
        {          
            PanelFunction.Visible = true;
            Button1.Visible = true;
            btn_Del.Visible = true;
            //btn_Edit.Visible = true;
            //btn_removeQuit.Visible = true;
            btn_removeBlack.Visible = true;
        }
        Label1.Text = "在职员工";
        HiddenField1.Value = "1";
        bind();
    }
    protected void Ibtn_quit_Click(object sender, ImageClickEventArgs e)
    {
        if (positionId == -1 || positionId == -2)
        {         
            PanelFunction.Visible = true;
            Button1.Visible = false;
            btn_Del.Visible = true;
           // btn_Edit.Visible = false;
            btn_removeQuit.Visible = false;
            btn_removeBlack.Visible = true;
        }
        Label1.Text = "正常离职";
        HiddenField1.Value = "2";
        bind();
    }
    protected void Ibtn_black_Click(object sender, ImageClickEventArgs e)
    {
        Label1.Text = "黑名单";
        PanelFunction.Visible = false;

        HiddenField1.Value = "3";
        bind();
    }

    /// <summary>
    /// 根据不同权限显示功能按钮
    /// </summary>
    private void ShowPannel()
    {
        if (permissinons == 1 || permissinons == 2)  //管理员行政主管
        {
            FuncBtnList.Visible = true;
            PanelFunction.Visible = true;
            PanelList.Visible = true;
        }
        else
        {
            FuncBtnList.Visible = true;
            PanelFunction.Visible = false;
            PanelList.Visible = true;
        }
    }

    /// <summary>
    /// 显示部门名称
    /// </summary>
    /// <param name="n">部门id</param>
    /// <returns></returns>
    protected string ShowPartmentName(string n)
    {
        SqlConnection conn = CreateConn();
        string name = "";
        string selectCmsStr = "select Department from tb_Department where ID='" + n + "'";

        try
        {
            SqlCommand selectCmd = new SqlCommand(selectCmsStr, conn);

            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = selectCmd;

            DataSet ds = new DataSet();
            da.Fill(ds);
            name = ds.Tables[0].Rows[0][0].ToString();

        }
        catch (Exception ex)
        {
        }

        return name;
    }


    /// <summary>
    /// 显示职务名称
    /// </summary>
    /// <param name="n">职务id</param>
    /// <returns></returns>
    protected string ShowPositionName(string n)
    {
        SqlConnection conn = CreateConn();
        string name = "";
        string selectCmsStr = "select Position from tb_Position where ID='" + n + "'";

        try
        {
            SqlCommand selectCmd = new SqlCommand(selectCmsStr, conn);

            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = selectCmd;

            DataSet ds = new DataSet();
            da.Fill(ds);
            name = ds.Tables[0].Rows[0][0].ToString();

        }
        catch (Exception ex)
        {
        }

        return name;
    }

    protected void btn_Back_Click(object sender, EventArgs e)
    {
        ShowBirNamePinel.Visible = false;
        ShowPannel();
        bind();
    }

    /// <summary>
    /// 根据不同权限修改按钮是否可用
    /// </summary>
    private void EditEnable()
    {
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            GridViewRow row = GridView1.Rows[i];
            HyperLink hyperlink = ((HyperLink)row.FindControl("UserEdit"));

            if (permissinons == 1 || permissinons == 2)
            {
                hyperlink.Enabled = true;
            }
            else
            {
                hyperlink.Enabled = false;
            }
            
            /*bool isCheck = ((CheckBox)row.FindControl("SelectEmployee")).Checked;
            string temp = GridView1.DataKeys[GridView1.Rows[i].RowIndex].ToString();
            int EmployeeID = Convert.ToInt32(GridView1.DataKeys[GridView1.Rows[i].RowIndex].Value);*/
        }
    }
}